<?php

namespace App\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Auth;
use App\Http\Resources\UserResource;
use App\Models\User;
use App\Rules\CodeRule;
use Hash;
use Illuminate\Contracts\Routing\ResponseFactory;
use Illuminate\Contracts\Container\BindingResolutionException;
use Illuminate\Database\Eloquent\MassAssignmentException;
use Illuminate\Http\Response;
use InvalidArgumentException;

/**
 * 用户
 * @package App\Api
 */
class UserController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth:sanctum');
        $this->middleware(['module'])->only(['email']);
        $this->authorizeResource(User::class, 'user');
    }

    /**
     * 获取当前用户资料
     * @return UserResource
     */
    public function info()
    {
        return new UserResource(Auth::user());
    }

    /**
     * 更新用户资料
     * @param Request $request
     * @param User $user
     * @return array
     * @throws MassAssignmentException
     * @throws InvalidArgumentException
     */
    public function update(Request $request, User $user)
    {
        $user->fill($request->input())->save();
        return $this->message('用户资料修改成功');
    }

    /**
     * 修改密码
     * @param Request $request
     * @param User $user
     * @return Response|ResponseFactory|array
     * @throws InvalidArgumentException
     * @throws BindingResolutionException
     */
    public function password(Request $request)
    {
        $user = Auth::user();
        if (!Hash::check($request->old_password, $user->password)) {
            return $this->error('原密码输入错误', 403);
        }

        $request->validate([
            'old_password' => ['required'],
            'password' => ['required', 'confirmed']
        ], ['password.confirmed' => '确认密码输入错误']);

        $user->password = Hash::make($request->password);
        $user->save();
        return $this->message('密码修改成功');
    }

    /**
     * 绑定邮箱
     * @param Request $request
     * @return void
     */
    public function email(Request $request)
    {
        $request->validate([
            'email' => ['required', 'email'],
            'code' => ['required', new CodeRule($request->email)],
        ], ['code.required' => '验证码不能为空']);

        $user = Auth::user();
        $user->email = $request->email;
        $user->save();
        return $this->message('邮箱修改成功', $user);
    }

    /**
     * 绑定手机
     * @param Request $request
     * @return void
     */
    public function mobile(Request $request)
    {
        $request->validate([
            'mobile' => ['required', 'regex:\d{11}'],
            'code' => ['required', new CodeRule($request->mobile)],
        ], ['code.required' => '验证码不能为空']);

        $user = Auth::user();
        $user->mobile = $request->mobile;
        $user->save();
        return $this->message('手机号绑定成功', $user);
    }
}
